package gao.test.tomcat.util.net.bio;

import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicInteger;

public class Server {
	
	private AtomicInteger count = new AtomicInteger(0);
	
	private int port = 8765;
	private ServerSocket serverSocket;

	public Server() throws IOException {
		//serverSocket = new ServerSocket(port, 3); // 连接请求队列的长度为3
		serverSocket = new ServerSocket(port); // 连接请求队列的长度为3
		System.out.println("服务器启动");
	}

	public void service() {
		while (true) {
			Socket socket = null;
			try {
				socket = serverSocket.accept(); // 从连接请求队列中取出一个连接
				System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
				this.read(socket);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (socket != null)
						socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	
	
	private void read(Socket socket) {
        try {
        	int incrementAndGet = count.incrementAndGet();
        	BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        	//读取客户端发送来的消息
            String mess = br.readLine();
            System.out.println("客户端：       "+mess+" ,  序号   ："+incrementAndGet);
            OutputStream bw = socket.getOutputStream();
            
            String str16 = "我已经收到你的消息了 \n";
            
            bw.write(str16.getBytes("GBK"));
            bw.flush();
            bw.close();
            br.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
	
	
	public static String strTo16(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;
    }
	

	public static void main(String args[]) throws Exception {
		Server server = new Server();
		server.service();
		Thread.sleep(60000 * 10); // 睡眠10分钟
		// server.service();
	}
}
